package ils.services;

import ils.domain.catalog.model.Book;
import ils.domain.catalog.model.BookRepository;
import ils.domain.catalog.model.Category;
import ils.util.HibernateSession;
import ils.util.HibernateSessionManager;
import ils.web.model.WBook;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

public class SearchServiceImpl implements SearchService
{
    private BookRepository bookRepository;
    HibernateSessionManager hibernateSessionManager;

    @Override
    public List<WBook> searchBooks(String type, String searchTerm) throws Exception
    {
        try(HibernateSession session = hibernateSessionManager.getSession())
        {
            List<ils.domain.catalog.model.Book> books = bookRepository.searchBooks(searchTerm, null);
            List<WBook> wbooks = new ArrayList<WBook>();
            for(Book book : books)
            {
                WBook wbook = new WBook();
                BeanUtils.copyProperties(wbook, book);
                Category category = book.getCategory();
                if(category != null)
                {
                    wbook.setCategoryId(category.getId());
                    wbook.setCategoryName(category.getName());
                }
                wbooks.add(wbook);
            }
            return wbooks;
        }
    }

    @Override
    public WBook getBookDetails(int bookId) throws Exception
    {
        try(HibernateSession session = hibernateSessionManager.getSession())
        {
            Book book = bookRepository.getBook(bookId);
            WBook wbook = new WBook();
            BeanUtils.copyProperties(wbook, book);
            Category category = book.getCategory();
            if(category != null)
            {
                wbook.setCategoryId(category.getId());
                wbook.setCategoryName(category.getName());
            }
            return wbook;
        }
    }

    public void setBookRepository(BookRepository bookRepository)
    {
        this.bookRepository = bookRepository;
    }

    public void setHibernateSessionManager(HibernateSessionManager hibernateSessionManager) {
        this.hibernateSessionManager = hibernateSessionManager;
    }
}
